package com.hanlin.backend.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanlin.backend.common.entity.HlUser;
import com.hanlin.backend.common.entity.HlUserInfo;
import com.hanlin.backend.common.service.HlServiceFactory;
import com.hanlin.backend.common.util.MD5Utils;
import com.hanlin.backend.dto.RoleDto;
import com.hanlin.backend.dto.UserInfo;
import com.hanlin.backend.mapper.HlUserMapper;
import com.hanlin.backend.service.HlRoleService;
import com.hanlin.backend.service.HlUserInfoService;
import com.hanlin.backend.service.HlUserRoleService;
import com.hanlin.backend.service.HlUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hl.yuan
 * @since 2020-12-22
 */
@Service
@Slf4j
public class HlUserServiceImpl extends ServiceImpl<HlUserMapper, HlUser> implements HlUserService {

    @Autowired
    private HlRoleService roleService;

    @Autowired
    private HlUserRoleService userRoleService;

    @Autowired
    private HlUserInfoService userInfoService;

    @Override
    public HlUser findByUserName(String userName) {
        if (StrUtil.isEmpty(userName)) {
            log.error("传入的name为空：{}", userName);
            return null;
        }
        QueryWrapper<HlUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", userName);
        // 查询第一个
        HlUser user = getBaseMapper().selectOne(queryWrapper);
        return user;
    }

    @Override
    public IPage<UserInfo> getTableList(UserInfo userInfo) {
        IPage iPage = userInfo.buildPage();
        IPage<UserInfo> users = getBaseMapper().getTableUserList(iPage, userInfo);
        List<UserInfo> records = users.getRecords();

        records.forEach(item -> {
            int userid = item.getUserId();
            // 查出用户对应的角色信息
            List<RoleDto> roleByUserId = roleService.getRoleByUserId(userid);
            StringBuffer roleName = new StringBuffer();
            roleByUserId.forEach(role -> {
                if (roleName.length() > 0) {
                    roleName.append(",");
                }
                roleName.append(role.getRoleName());
            });
            item.setRoleName(roleName.toString());
        });
        return users;
    }

    @Override
    @Cacheable(value = "userById", key = "'userId:'+#userId")
    public UserInfo getUserById(Integer userId) {
        if (userId == null) {
            log.error("userID为空");
            return null;
        }
        UserInfo userInfo = getBaseMapper().getUserById(userId);
        if (userInfo != null) {
            List<RoleDto> roleByUserId = roleService.getRoleByUserId(userId);
            List<Integer> list = new ArrayList<>();
            roleByUserId.forEach(item -> {
                Integer roleId = item.getRoleId();
                list.add(roleId);
            });
            userInfo.setRoleId(list);
        }
        return userInfo;
    }

    @Override
    public List<Map> getUserByRoleId(Integer roleId) {
        if (roleId==null) {
            return null;
        }
        List<Map> userInfo = getBaseMapper().getUserByRoleId(roleId);
        return userInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "userById", key = "'userId:'+#userInfo.userId")
    public void userSave(UserInfo userInfo) {
        // 用户保存
        Integer userId = userInfo.getUserId();
        UserInfo user = this.getUserById(userId);
        if (user != null) {
            // 处理角色信息
            userRoleService.saveUserRole(userInfo.getRoleId(), userId);
            // 获取用户信息
            HlUserInfo hlUserInfo = userInfoService.getUserInfoByUserId(userId);
            if (hlUserInfo != null) {
                hlUserInfo.setAddress(userInfo.getAddress());
                hlUserInfo.setAge(userInfo.getAge());
                hlUserInfo.setSex(userInfo.getSex());
                hlUserInfo.setMail(userInfo.getMail());
                hlUserInfo.setPhone(userInfo.getPhone());
                hlUserInfo.setUserName(userInfo.getUserName());
                userInfoService.saveOrUpdate(hlUserInfo);
            }
        } else {
            // 新增用户
            HlUser hlUser = new HlUser();
            hlUser.setUsername(userInfo.getAccountName());
            // 获取全局参数
            String passWord = HlServiceFactory.getSettingService().getSetting("COMMON", "PASSWORD", "111");
            hlUser.setPassword(MD5Utils.encrypt(userInfo.getAccountName(), passWord));
            saveOrUpdate(hlUser);
            // 保存用户基础信息
            HlUserInfo hlUserInfo = new HlUserInfo();
            hlUserInfo.setAddress(userInfo.getAddress());
            hlUserInfo.setAge(userInfo.getAge());
            hlUserInfo.setSex(userInfo.getSex());
            hlUserInfo.setMail(userInfo.getMail());
            hlUserInfo.setPhone(userInfo.getPhone());
            hlUserInfo.setUserName(userInfo.getUserName());
            // bug 应该可以通过hlUser.getId()得到ID
            hlUserInfo.setUserId(hlUser.getId());
            userInfoService.saveOrUpdate(hlUserInfo);
            // 保存用户与角色信息
            userRoleService.saveUserRole(userInfo.getRoleId(), hlUser.getId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(List<Integer> userIds) {
        if (userIds != null && userIds.size() > 0) {
            // 删除用户信息
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.in("user_id", userIds);
            userInfoService.remove(wrapper);
            // 删除用户与角色的中间表
            userRoleService.remove(wrapper);
            // 删除 用户
            this.removeByIds(userIds);
        }
    }
}
